<?php
class OrdersController extends AppController {
	var $name = 'Orders';
    var $components = array('Email');
    var $status = array(
        'N' => 'Canceled',
        'P' => 'Pending',
        'I' => 'Processing',
        'S' => 'Shipped',
        'D' => 'Denied',
        'F' => 'Failed',
        'R' => 'Refunded',
        'C' => 'Complete'
    );
    var $country = array(
        'AR' => 'Argentina',
        'AU' => 'Australia',
        'BS' => 'Bahamas',
        'BH' => 'Bahrain',
        'BZ' => 'Belize',
        'BM' => 'Bermuda',
        'BR' => 'Brazil',
        'VG' => 'British Virgin Islands',
        'CA' => 'Canada',
        'KY' => 'Cayman Islands',
        'CL' => 'Chile',
        'CN' => 'China',
        'CR' => 'Costa Rica',
        'DO' => 'Dominican Republic',
        'EC' => 'Ecuador',
        'GU' => 'Guam',
        'GT' => 'Guatemala',
        'HK' => 'Hong Kong',
        'IN' => 'India',
        'IL' => 'Israel',
        'JP' => 'Japan',
        'JO' => 'Jordan',
        'KW' => 'Kuwait',
        'MO' => 'Macau',
        'MY' => 'Malaysia',
        'MX' => 'Mexico',
        'NZ' => 'New Zealand',
        'PA' => 'Panama',
        'PE' => 'Peru',
        'PH' => 'Philippines',
        'SA' => 'Saudi Arabia',
        'SG' => 'Singapore',
        'ZA' => 'South Africa',
        'KR' => 'South Korea',
        'LK' => 'Sri Lanka',
        'TW' => 'Taiwan',
        'TH' => 'Thailand',
        'VI' => 'U.S. Virgin Islands',
        'AE' => 'United Arab Emirates',
        'US' => 'United States',
        'UM' => 'United States Minor Outlying Islands',
        'VE' => 'Venezuela'
    );

    public function proceed () {
        if (!$this->_checkLogged()) {
            return;
        }

        $info = $this->Session->read('Info');
        $id   = $this->Session->read('Member.id');
        $cart = $this->Session->read('Cart');
        $total = $info['shipping'];

        foreach ($cart as $i=>$c) { // purchase items
            $data2[$i] = array(
                'product_id' => $c['id'],
                'name'       => $c['name'],
                'price'      => $c['price'],
                'quantity'   => $c['qty']
            );
            $total += ($c['price'] * $c['qty']);
        }

        $this->loadModel('Member');
        $m = $this->Member->read(array(
            'username', 'name', 'telephone', 'fax'
        ), $id);

        $stts = ($info['payment_method'] == 'Credit Card Payment') ? 'N' : 'P';
        $data = array(
            'Order' => array(
                'member_id' => $id,
                'name'      => $m['Member']['name'],
                'telephone' => $m['Member']['telephone'],
                'fax'       => $m['Member']['fax'],
                'email'     => $m['Member']['username'],
                'address'   => $info['address'],
                'city'      => $info['city'],
                'postcode'  => $info['postcode'],
                'zone'      => $info['state'],
                'country'   => $info['country'],
                'payment_method' => $info['payment_method'],
                'comment'   => $info['comment'],
                'shipping'  => $info['shipping'],
                'total'     => $total,
                'status'    => $stts,
                'ip'        => env('REMOTE_ADDR')
            )
        );
        if ($sid = $this->Session->read('Saved.id')) {
            $data['Order']['id'] = $sid;
        }

        if ($this->Order->save($data)) {
            $this->Session->write('Saved.id', $this->Order->id);

            foreach ($data2 as $i=>$v) {
                $data2[$i]['order_id'] = $this->Order->id;
            }

            $this->loadModel('OrderProduct');
            $this->OrderProduct->deleteAll('order_id='.$this->Order->id);
            $this->OrderProduct->saveAll($data2);
            $this->_gateway($info['payment_method'], $this->Order->id, $data);
        } else {
            $this->Session->setFlash('<h4>'.__('Fail to proceed at this time, please try again.',true).'</h4>', 'default', array('class'=>'boxError'));
            $this->redirect('/pages/confirm');
        }
    } // proceed

    public function ipay_callback () {
        $status = $this->params['form']['Status'];

        $expected_sign = $this->params['form']['Signature'];
        $payment_id    = $this->params['form']['PaymentId'];
        $currency      = $this->params['form']['Currency'];
        $status        = $this->params['form']['Status'];
        $refNo         = trim(stripslashes($this->params['form']['RefNo']));
        $hashAmount    = str_replace(array(',','.'), '', $this->params['form']['Amount']);
        $ipaySignature = '';

        $str = $this->merchantKey.$this->merchantCode.$payment_id.$refNo.$hashAmount.$currency.$status;
        $str = sha1($str);

        for ($i=0; $i<strlen($str); $i=$i+2) {
            $ipaySignature .= chr(hexdec(substr($str, $i, 2)));
        }
        $check_sign = base64_encode($ipaySignature);

        /*$result = $this->_requery();
        if ($result != '00') {
            switch ($result) {
                case 'Invalid parameters':
                $mesg = 'Parameters pass in incorrect';
                break;

                case 'Record not found':
                $mesg = 'Cannot found the record';
                break;

                case 'Incorrect amount':
                $mesg = 'Amount different';
                break;

                case 'Payment fail':
                $mesg = 'Payment fail';

                case 'M88Admin':
                $mesg = 'Payment status updated by Mobile88 Admin(Fail)';
                break;
            }
            $status = 0;
            $this->Session->setFlash('<h4>'.__($mesg, true).'</h4>', 'default', array('class'=>'boxError'));
        }*/

        if ($status == '1' && $check_sign == $expected_sign) {
            $this->Session->del('Cart');
            $this->Session->del('Info');
            $this->Session->del('Saved.id');

            $data['OrderHistory'] = array(
                'order_id' => $refNo,
                'status'   => 'I',
                'comment'  => 'Payment made via iPay88'
            );
            $this->loadModel('OrderHistory');
            $this->OrderHistory->save($data);

            $this->Order->id = $refNo;
            $this->Order->saveField('status', 'I');

            $this->_sendMail($refNo);

            $this->pageTitle = __('Payment Success',true);
            $this->render('success');
        } else {
            $this->Order->id = $refNo;
            $this->Order->saveField('status', 'D');

            $this->pageTitle = __('Payment Declined',true);
            $this->render('failure');
        }
    } // ipay_callback

    public function nbepay_callback () {
        $status = $this->params['form']['status'];
        $refNo  = trim(stripslashes($this->params['form']['orderid']));

        if ($status == '00') {
            $this->Session->del('Cart');
            $this->Session->del('Info');
            $this->Session->del('Saved.id');

            $data['OrderHistory'] = array(
                'order_id' => $refNo,
                'status'   => 'I',
                'comment'  => 'Payment made via Netbuilder.'."\n" .
                              'Transaction Id: '.$this->params['form']['tranID']."\n" .
                              'Bank Approval Code: '.$this->params['form']['appcode']
            );
            $this->loadModel('OrderHistory');
            $this->OrderHistory->save($data);

            $this->Order->id = $refNo;
            $this->Order->saveField('status', 'I');

            $this->_sendMail($refNo);

            $this->pageTitle = __('Payment Success',true);
            $this->render('success');
        } else {
            $this->Order->id = $refNo;
            $this->Order->saveField('status', 'D');

            $this->pageTitle = __('Payment Declined',true);
            $this->render('failure');
        }
    } // nbepay_callback

    public function history () {
        if (!$this->_checkLogged()) {
            return;
        }

        $this->helpers = array_merge($this->helpers, array('Time'));

        if ($this->Session->read('Member.role') == 'A') { // admin
            $cond = array('Order.status <>' => 'N');
        } else {
            $cond = array(
                'Order.member_id' => $this->Session->read('Member.id')
            );
        }

        $params = array(
            'limit'      => 6,
            'conditions' => $cond,
            'order'      => array('Order.id DESC')
        );
        $this->paginate = $params;

        $this->pageTitle = __('My Order History', true);
        $this->set('orders', $this->paginate());
        $this->set('status', $this->status);
    } // history

    public function view ($id) {
        if (!$this->_checkLogged()) {
            return;
        }

        if ($this->Session->read('Member.role') == 'A') { // admin
            $cond = array('Order.id' => $id);
        } else {
            $cond = array(
                'Order.id'        => $id,
                'Order.member_id' => $this->Session->read('Member.id')
            );
        }

        $data = $this->Order->find('first', array('conditions' => $cond));

        $this->pageTitle = __('Order Invoice', true);
        $this->set('data', $data);
        $this->set('status', $this->status);
    } // view

    public function update () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $id = $this->params['form']['id'];
        $data['OrderHistory'] = array(
            'order_id' => $id,
            'status'   => $this->params['form']['status'],
            'comment'  => $this->params['form']['comment']
        );
        $this->loadModel('OrderHistory');
        $this->OrderHistory->save($data);

        $this->Order->id = $id;
        $this->Order->saveField('status', $this->params['form']['status']);

        $this->Session->setFlash('<h4>'.__('Order status have been updated.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
        $this->redirect('/orders/view/'.$id);
    } // update

    public function bankin2 () {

    }


    private function _gateway ($method, $oid, $info) {
        if ($method == 'Credit Card Payment') {
            $params = array(
                'amount'      => $info['Order']['total'],
                'orderid'     => $oid,
                'bill_name'   => $info['Order']['name'],
                'bill_email'  => $info['Order']['email'],
                'bill_mobile' => $info['Order']['telephone'],
                'bill_desc'   => 'Items on '.date('d/m/Y').' Order No: '.$oid,
                'returnurl'   => env('HTTP_HOST').'/'.$this->base.'/orders/nbepay_callback',
                'vcode'       => md5($info['Order']['total'].'carelatex'.$oid.'2edc038541fb902255b399d94ccddec9')
            );

            if ($iso = array_search($info['Order']['country'], $this->country)) {
                $params['country'] = $iso;
            }

            $this->redirect('https://www.onlinepayment.com.my/NBepay/pay/carelatex/?'.http_build_query($params));
        } else if ($method == 'Bank Transfer' || $method == 'COD (cash on delivery)') {
            $this->Session->del('Cart');
            $this->Session->del('Info');
            $this->Session->del('Saved.id');

            $data['OrderHistory'] = array(
                'order_id' => $oid,
                'status'   => 'P',
                'comment'  => 'You can deposit cash, bank-in, transfer from internet or cheque to Care Latex\'s bank account as below:'."\n\n".
                              'Company Name - Care Latex Sdn Bhd (702290-T)'."\n".
                              'Maybank Acc. No.- 5144 4010 7046'."\n\n".
                              'Your order will not ship until we receive payment.'
            );
            $this->loadModel('OrderHistory');
            $this->OrderHistory->save($data);

            $this->_sendMail($oid);

            $this->pageTitle = __('Checkout Success',true);
            $this->render('bankin');
        } else { // ipay88
            $signature  = '';
            $ordAmount  = number_format($info['Order']['total'], 2);
            $hashAmount = str_replace('.', '', str_replace(',', '', $ordAmount));

            $str = sha1($this->merchantKey.$this->merchantCode.'2'.$oid.$hashAmount.'MYR1');

            for ($i=0; $i<strlen($str); $i=$i+2) {
                $signature .= chr(hexdec(substr($str, $i, 2)));
            }

            $signature = base64_encode($signature);

            $data = array(
                'MerchantCode' => $this->merchantCode,
                'RefNo'        => $oid,
                'Amount'       => $ordAmount,
                'Currency'     => 'MYR',
                'UserName'     => $info['Order']['name'],
                'UserEmail'    => $info['Order']['email'],
                'UserContact'  => $info['Order']['telephone'],
                'Remark'       => 'Items on '.date('d/m/Y').' Order No: '.$oid,
                'Signature'    => $signature
            );

            $this->set('data', $data);
            $this->render('payment');
        }
    } // _gateway

    private function _requery () {
        $query = 'http://www.mobile88.com/epayment/enquiry.asp?MerchantCode='.$this->merchantCode.'&RefNo='.$this->params['form']['RefNo'].'&Amount='.$this->params['form']['Amount'];
        $url   = parse_url($query);
        $host  = $url['host'];
        $path  = $url['path'].'?'.$url['query'];
        $timeout = 1;

        $fp = fsockopen ($host, 80, $errno, $errstr, $timeout);

        if ($fp) {
            fputs($fp, 'GET '.$path." HTTP/1.0\nHost: ".$host."\n\n");
            while (!feof($fp)) {
                $buf .= fgets($fp, 128);
            }
            $lines  = split("\n", $buf);
            $result = $lines[count($lines)-1];
            fclose($fp);
        } else {
            $result = 'No response from payment gateway server.';
        }

        return $result;
    }

    private function _sendMail ($id) {
        $data = $this->Order->find('first', array(
            'conditions' => array('Order.id' => $id))
        );

        $sitename = Configure::read('site.sitename');
        $domain   = str_replace('www.', '', env('HTTP_HOST'));
        $delivery = (Configure::read('debug') > 1) ? 'mail' : 'mail';

        // alert admin of new order
        $this->Email->to       = 'marcuxleong@gmail.com';
        $this->Email->replyTo  = $data['Order']['email'];
        $this->Email->from     = $sitename.' <noreply@'.$domain.'>';
        $this->Email->subject  = 'New order made by '.$data['Order']['name'];
        $this->Email->template = 'order';
        $this->Email->sendAs   = 'text';
        $this->Email->delivery = $delivery;

        $dt = array(
            'sitename' => $sitename,
            'id'       => $id,
            'date'     => $data['Order']['created'],
            'name'     => $data['Order']['name'],
            'tel'      => $data['Order']['telephone'],
            'email'    => $data['Order']['email'],
            'status'   => $this->status[$data['Order']['status']],
            'items'    => $data['OrderProduct'],
            'shipping' => $data['Order']['shipping'],
            'total'    => number_format(($data['Order']['shipping']+$data['Order']['total']), 2),
            'url'      => Router::url('/orders/view/'.$id, true),
            'comment'  => $data['Order']['comment']
        );

        $this->set($dt);
        $this->Email->send();
        $this->Email->reset();

        // send receipt to client
        $this->Email->to       = $data['Order']['email'];
        $this->Email->replyTo  = $sitename.' <info@'.$domain.'>';
        $this->Email->from     = $sitename.' <noreply@'.$domain.'>';
        $this->Email->subject  = 'Receipt for Your Payment to '.$sitename;
        $this->Email->template = 'order2';
        $this->Email->sendAs   = 'text';
        $this->Email->delivery = $delivery;
        //$this->set($dt);
        $this->Email->send();
    } // _sendMail
} // OrdersController
?>